package com.ruoyi.fztz.clxhtb.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.WordUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.fztz.clxhtb.domain.Clxhtb;
import com.ruoyi.fztz.clxhtb.domain.ClxhtbFj;
import com.ruoyi.fztz.clxhtb.domain.ClxhtbSysb;
import com.ruoyi.fztz.clxhtb.domain.ClxhtbXhcl;
import com.ruoyi.fztz.clxhtb.service.IClxhtbService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.IntStream;

/**
 * 材料消耗填报Controller
 *
 * @author huacai
 * @date 2024-11-20
 */
@RestController
@RequestMapping("/fztz/clxhtb")
public class ClxhtbController extends BaseController {
    @Resource
    private IClxhtbService clxhtbService;

    /**
     * 查询材料消耗填报列表
     */
    @PreAuthorize("@ss.hasPermi('fztz:clxhtb:list')")
    @GetMapping("/list")
    public TableDataInfo list(Clxhtb clxhtb) {
        startPage();
        List<Clxhtb> list = clxhtbService.selectClxhtbList(clxhtb);
        return getDataTable(list);
    }

    /**
     * 查询材料消耗填报列表(用于 研发活动证明(村料消耗)选择 组件)
     */
    @GetMapping("/selectClXhDxList")
    public TableDataInfo selectClXhDxList(Clxhtb clxhtb) {
        startPage();
        List<Clxhtb> list = clxhtbService.selectClXhDxList(clxhtb);
        return getDataTable(list);
    }

    /**
     * 导出材料消耗填报列表
     */
    @PreAuthorize("@ss.hasPermi('fztz:clxhtb:export')")
    @Log(title = "材料消耗填报", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Clxhtb clxhtb) {
        List<Clxhtb> list = clxhtbService.selectClxhtbList(clxhtb);
        ExcelUtil<Clxhtb> util = new ExcelUtil<Clxhtb>(Clxhtb.class);
        util.exportExcel(response, list, "材料消耗填报数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Clxhtb> util = new ExcelUtil<Clxhtb>(Clxhtb.class);
        util.importTemplateExcel(response, "材料消耗填报数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "材料消耗填报", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('fztz:clxhtb:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<Clxhtb> util = new ExcelUtil<Clxhtb>(Clxhtb.class);
        InputStream inputStream = file.getInputStream();
        List<Clxhtb> list = util.importExcel(inputStream);
        inputStream.close();
        int count = clxhtbService.batchInsertClxhtb(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取材料消耗填报详细信息
     */
    @PreAuthorize("@ss.hasPermi('fztz:clxhtb:query')")
    @GetMapping(value = "/{clxhtbId}")
    public AjaxResult getInfo(@PathVariable("clxhtbId") String clxhtbId) {
        return success(clxhtbService.selectClxhtbByClxhtbId(clxhtbId));
    }

    /**
     * 获取材料消耗填报与实(试)验过程消耗的材料信息
     */
    @GetMapping(value = "/xhcl/{clxhtbId}")
    public AjaxResult selectClxhtbXhclByClxhtbId(@PathVariable("clxhtbId") String clxhtbId) {
        return success(clxhtbService.selectClxhtbXhclByClxhtbId(clxhtbId));
    }

    /**
     * 获取实(试)验过程使用的设备信息
     */
    @GetMapping(value = "/sysb/{clxhtbId}")
    public AjaxResult selectClxhtbSySbByClxhtbId(@PathVariable("clxhtbId") String clxhtbId) {
        return success(clxhtbService.selectClxhtbSySbByClxhtbId(clxhtbId));
    }

    /**
     * 新增材料消耗填报
     */
    @PreAuthorize("@ss.hasPermi('fztz:clxhtb:add')")
    @Log(title = "材料消耗填报", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Clxhtb clxhtb) {
        clxhtb.setUserId(Math.toIntExact(getUserId())); //用户ID
        clxhtb.setDeptId(Math.toIntExact(getDeptId())); //部门ID
        clxhtb.setCreateBy(getUsername()); //创建人
        clxhtb.setIdWhere("存在");
        return toAjax(clxhtbService.insertClxhtb(clxhtb));
    }

    /**
     * 修改材料消耗填报
     */
    @PreAuthorize("@ss.hasPermi('fztz:clxhtb:edit')")
    @Log(title = "材料消耗填报", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Clxhtb clxhtb) {
        return toAjax(clxhtbService.updateClxhtb(clxhtb));
    }

    /**
     * 删除材料消耗填报
     */
    @PreAuthorize("@ss.hasPermi('fztz:clxhtb:remove')")
    @Log(title = "材料消耗填报", businessType = BusinessType.DELETE)
    @DeleteMapping("/{clxhtbIds}")
    public AjaxResult remove(@PathVariable String[] clxhtbIds) {
        return toAjax(clxhtbService.deleteClxhtbByClxhtbIds(clxhtbIds));
    }

    /**
     * 获得材料消耗填报主键ID (UUID)
     */
    @GetMapping("/getClXhTbId")
    public AjaxResult getClXhTbId() {
        String getClXhTbId = IdUtils.fastSimpleUUID();
        return success(getClXhTbId);
    }

    /**
     * 查询某个xmsbId在表中出现过几次
     */
    @GetMapping("/selectXmsbIdCountByClxhtb/{clxhtbId}")
    public AjaxResult selectXmsbIdCountByClxhtb(@PathVariable("clxhtbId") String clxhtbId) {
        return clxhtbService.selectXmsbIdCountByClxhtb(clxhtbId);
    }

    /**
     * 新增附件
     */
    @PostMapping("/add/File/By/subId")
    public AjaxResult insertClxhtbFjByClxhtbId(@RequestBody ClxhtbFj clxhtbFj) {
        return toAjax(clxhtbService.insertClxhtbFjByClxhtbId(clxhtbFj));
    }

    /**
     * 根据ID查询附件列表
     */
    @GetMapping("/get/FileList/By/subId")
    public AjaxResult selectClxhtbFjList(String sId) {
        ClxhtbFj clxhtbFj = new ClxhtbFj();
        clxhtbFj.setClxhtbId(sId);
        return AjaxResult.success(clxhtbService.selectClxhtbFjList(clxhtbFj));
    }

    /**
     * 删除材料消耗填报附件
     */
    @Log(title = "材料消耗填报附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/fj/{fjIds}")
    public AjaxResult deleteClxhtbFjByFjIds(@PathVariable Integer[] fjIds) {
        return toAjax(clxhtbService.deleteClxhtbFjByFjIds(fjIds));
    }

    /**
     * 根据模板导出word
     * @param response
     * @return
     */
    @Log(title = "根据模板导出word", businessType = BusinessType.EXPORT)
    @GetMapping("/exportWord/{clxhtbId}")
    public AjaxResult exportWord(@PathVariable("clxhtbId") String clxhtbId, HttpServletRequest request, HttpServletResponse response) {
        Clxhtb clxhtb = clxhtbService.selectClxhtbByClxhtbId(clxhtbId);
        String xmName = clxhtb.getXmName(); //项目名称
        String xmBh = clxhtb.getXmBh(); //项目编号

        //指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String jlQTime = sdf.format(clxhtb.getJlQTime()); //记录开始时间
        String jlZTime = sdf.format(clxhtb.getJlZTime()); //记录结束时间

        String jlCs = clxhtb.getJlCs(); //记录次数
        String bcKyMd = clxhtb.getBcKyMd(); //本次科研目的
        String bcKyHdQk = clxhtb.getBcKyHdQk(); //本次科研活动情况
        String bcKyJg = clxhtb.getBcKyJg(); //本次科研结果
        String bcCyKyRy = clxhtb.getBcCyKyRy(); //本次参与的科研人员

        Clxhtb clxhtbXhCl = clxhtbService.selectClxhtbXhclByClxhtbId(clxhtbId);
        List<ClxhtbXhcl> clxhtbXhclList = clxhtbXhCl.getClxhtbXhclList(); //消耗的材料表

        if (clxhtbXhclList != null) {
            IntStream.range(0, clxhtbXhclList.size())
                    .forEach(i -> {
                        ClxhtbXhcl item = clxhtbXhclList.get(i);
                        if (item != null) {
                            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM");
                            Date date = item.getwLlYf();
                            item.setwLlYfToString(sd.format(date));
                        }
                    });
        }

        Clxhtb clxhtbSysb = clxhtbService.selectClxhtbSySbByClxhtbId(clxhtbId);
        List<ClxhtbSysb> clxhtbSysbList = clxhtbSysb.getClxhtbSysbList(); //使用设备表

        Map<String, Object> map = new HashMap<>();

        map.put("xmName", xmName);
        map.put("xmBh", xmBh);
        map.put("jlQTime", jlQTime);
        map.put("jlZTime", jlZTime);
        map.put("jlCs", jlCs);
        map.put("bcKyMd", bcKyMd);
        map.put("bcKyHdQk", bcKyHdQk);
        map.put("bcKyJg", bcKyJg);
        map.put("bcCyKyRy", bcCyKyRy);
        map.put("clxhtbXhclList", clxhtbXhclList);
        map.put("clxhtbSysbList", clxhtbSysbList);

        String str = "(第" + clxhtb.getJlCs() + ")次" + clxhtb.getXmName() +".docx";
        //获取yml配置地址
        String tempDir = "D:/ruoyi/uploadPath" + "/upload/";
        String name = WordUtil.easyPoiExport("static/word/fztz/clxhtb.docx", tempDir, str, map, request, response);
        return AjaxResult.success(name);
    }

}
